package com.tywj.lib.core.common.util

import android.app.Activity
import android.app.Application
import android.os.Bundle
import java.util.*

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/5/7
 *     desc   : 应用前后台状态监听工具类
 *     version: 1.0.0
 * </pre>
 */
object AppFrontBackTool {

    private val listenerList = LinkedList<OnAppStatusListener>()

    private val activityLifecycleCallbacks by lazy { AppActivityLifecycleCallbacks() }

    /**
     * 在Application初始化的时候使用
     */
    fun register(application: Application) {
        application.registerActivityLifecycleCallbacks(activityLifecycleCallbacks)
    }

    fun unRegister(application: Application) {
        application.unregisterActivityLifecycleCallbacks(activityLifecycleCallbacks)
    }

    private class AppActivityLifecycleCallbacks : Application.ActivityLifecycleCallbacks {
        private var activityStartCount = 0

        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}

        override fun onActivityStarted(activity: Activity) {
            activityStartCount++
            if (activityStartCount == 1) {
                listenerList.forEach { it.onFront() }
            }
        }

        override fun onActivityResumed(activity: Activity) {}

        override fun onActivityPaused(activity: Activity) {}

        override fun onActivityStopped(activity: Activity) {
            activityStartCount--
            if (activityStartCount == 0) {
                listenerList.forEach { it.onBack() }
            }
        }

        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?) {}

        override fun onActivityDestroyed(activity: Activity) {}
    }

    interface OnAppStatusListener {
        /**
         * 应用从后台切到前台
         */
        fun onFront() {}

        /**
         * 应用从前台切到后台
         */
        fun onBack() {}
    }

    fun addAppStatusListener(listener: OnAppStatusListener) {
        listenerList.add(listener)
    }

    fun removeAppStatusListener(listener: OnAppStatusListener) {
        listenerList.remove(listener)
    }
}